package com.sskj.hangqing.ui.activity;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sskj.common.adapter.MyFragmentPagerAdapter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.widget.ViewPagerSlide;
import com.sskj.hangqing.R2;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.BibiCoinType;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.CoinType;
import com.sskj.lib.bean.ColorEnum;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.CommonUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.lib.util.PopUtil;
import com.sskj.lib.widget.KChartMorePop;
import com.sskj.lib.widget.KChartPop;
import com.sskj.lib.widget.SpinnerPop;
import com.sskj.hangqing.R;
import com.sskj.hangqing.bean.rxbus.MarketCoinBean;
import com.sskj.hangqing.presenter.MarketActivityPresenter;
import com.sskj.hangqing.ui.fragment.ChartFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;

@Route(path = RConfig.APP_MARKET)
public class MarketActivity extends BaseActivity<MarketActivityPresenter> {
    @Autowired
    String code;
    @Autowired
    String qu;
    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R2.id.tvIndicator)
    TextView tvIndicator;
    @BindView(R2.id.tvMore)
    TextView tvMore;
    @BindView(R2.id.frameLayoutChart)
    FrameLayout frameLayoutChart;
    @BindView(R2.id.slidingTabLayout)
    SlidingTabLayout slidingTabLayout;
    @BindView(R2.id.viewPager)
    ViewPagerSlide viewPager;
    @BindView(R2.id.btTrade)
    Button btTrade;
    @BindView(R2.id.tvUSDT)
    TextView tvUSDT;
    @BindView(R2.id.tvHigh)
    TextView tvHigh;
    @BindView(R2.id.tvRMB)
    TextView tvRMB;
    @BindView(R2.id.tvRate)
    TextView tvRate;
    @BindView(R2.id.tvLow)
    TextView tvLow;
    @BindView(R2.id.tvVolume)
    TextView tvVolume;
    private ArrayList<ChartFragment> fragmentList = new ArrayList<>();
    String[] goodsType = {"minute", "minute15", "minute60", "hour4", "day", "minute", "minute15", "minute30", "week", "month"};
    private int currentIndex = 0;
    private SpinnerPop spinnerPop;
    private KChartPop kChartPop;
    private boolean isUpToggle = true;
    private boolean isDownToggle = false;
    private KChartMorePop kChartMorePop;

    @Override
    protected int getLayoutId() {
        return R.layout.app_activity_market_scroll;
    }

    @Override
    public MarketActivityPresenter getPresenter() {
        return new MarketActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        tvTitle.setText(code.replace("_", "/").toUpperCase());
        ArrayList<CustomTabEntity> customTabEntities = new ArrayList<>();
        customTabEntities.add(new TabItem(App.INSTANCE.getString(R.string.hang_marketActivity1_j), 0, 0));
        customTabEntities.add(new TabItem(App.INSTANCE.getString(R.string.hang_marketActivity2_j), 0, 0));
        customTabEntities.add(new TabItem(App.INSTANCE.getString(R.string.hang_marketActivity3_j), 0, 0));
        customTabEntities.add(new TabItem(App.INSTANCE.getString(R.string.hang_marketActivity4_j), 0, 0));
        customTabEntities.add(new TabItem(App.INSTANCE.getString(R.string.hang_marketActivity5_j), 0, 0));
        customTabEntities.add(new TabItem("", 0, 0));
        commonTabLayout.setTabData(customTabEntities);
        initTab();
        ClickUtil.click(btTrade, () -> {
            RxBus.getDefault().post(new BibiCoinType(code, qu));
            if (qu.equals(Constans.DANWEI)) {
                RxBus.getDefault().send(RxBusCode.CHANGE_THIRD);
            } else {
                RxBus.getDefault().send(RxBusCode.CHANGE_SECOND);

            }
            finish();
        });
        ClickUtil.click(200, tvMore, () -> {
            if (kChartMorePop == null) {
                kChartMorePop = new KChartMorePop(this);
                View contentView = kChartMorePop.getContentView();
                View tvOne = contentView.findViewById(R.id.tvOne);
                View tvFive = contentView.findViewById(R.id.tvFive);
                View tvThirty = contentView.findViewById(R.id.tvThirty);
                View tvWeek = contentView.findViewById(R.id.tvWeek);
                View tvMonth = contentView.findViewById(R.id.tvMonth);
                ClickUtil.click(tvOne, () -> {
                    selectTab(5);
                    commonTabLayout.setCurrentTab(5);
                    tvMore.setText(App.INSTANCE.getString(R.string.hang_marketActivity6_j));
                    kChartMorePop.dismiss();
                });
                ClickUtil.click(tvFive, () -> {
                    selectTab(6);
                    commonTabLayout.setCurrentTab(5);
                    tvMore.setText(App.INSTANCE.getString(R.string.hang_marketActivity7_j));
                    kChartMorePop.dismiss();
                });
                ClickUtil.click(tvThirty, () -> {
                    selectTab(7);
                    commonTabLayout.setCurrentTab(5);
                    tvMore.setText(App.INSTANCE.getString(R.string.hang_marketActivity8_j));
                    kChartMorePop.dismiss();
                });
                ClickUtil.click(tvWeek, () -> {
                    selectTab(8);
                    commonTabLayout.setCurrentTab(5);
                    tvMore.setText(App.INSTANCE.getString(R.string.hang_marketActivity9_j));
                    kChartMorePop.dismiss();
                });
                ClickUtil.click(tvMonth, () -> {
                    selectTab(9);
                    commonTabLayout.setCurrentTab(5);
                    tvMore.setText(App.INSTANCE.getString(R.string.hang_marketActivity10_j));
                    kChartMorePop.dismiss();
                });
                kChartMorePop.setBackground(0);
            }
            if (kChartMorePop.isShowing()) {
                kChartMorePop.dismiss();
            } else {
                kChartMorePop.showPopupWindow(commonTabLayout);
            }
        });
        ClickUtil.click(200, tvIndicator, () -> {
            if (kChartPop == null) {
                kChartPop = new KChartPop(this);
                View contentView = kChartPop.getContentView();
                TextView tvMa = contentView.findViewById(R.id.tvMa);
                TextView tvBoll = contentView.findViewById(R.id.tvBoll);
                TextView tvMacd = contentView.findViewById(R.id.tvMacd);
                TextView tvKdj = contentView.findViewById(R.id.tvKdj);
                TextView tvRsi = contentView.findViewById(R.id.tvRsi);
                TextView tvWr = contentView.findViewById(R.id.tvWr);
                ImageView ivUpToggle = contentView.findViewById(R.id.ivUpToggle);
                ImageView ivDownToggle = contentView.findViewById(R.id.ivDownToggle);
                ivUpToggle.setImageResource(R.mipmap.app_icon_show);
                ivDownToggle.setImageResource(R.mipmap.app_icon_show);
                ClickUtil.click(tvMa, () -> {
                    fragmentList.get(currentIndex).getKChartView().setMainDrawMaShow();
                    ivUpToggle.setImageResource(R.mipmap.app_icon_show);
                    kChartPop.dismiss();
                });
                ClickUtil.click(tvBoll, () -> {
                    fragmentList.get(currentIndex).getKChartView().setMainDrawBollShow();
                    ivUpToggle.setImageResource(R.mipmap.app_icon_show);
                    kChartPop.dismiss();

                });
                ClickUtil.click(ivUpToggle, () -> {
                    if (isUpToggle) {
                        isUpToggle = false;
                        ivUpToggle.setImageResource(R.mipmap.app_icon_hide);

                        fragmentList.get(currentIndex).getKChartView().setMainDrawNoneShow();
                    } else {
                        isUpToggle = true;
                        ivUpToggle.setImageResource(R.mipmap.app_icon_show);
                        fragmentList.get(currentIndex).getKChartView().setMainDrawMaShow();
                    }
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvMacd, () -> {
                    fragmentList.get(currentIndex).getKChartView().changeMACD();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvKdj, () -> {
                    fragmentList.get(currentIndex).getKChartView().changeKDJ();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvRsi, () -> {
                    fragmentList.get(currentIndex).getKChartView().changeRSI();
                    kChartPop.dismiss();

                });
                ClickUtil.click(tvWr, () -> {
                    fragmentList.get(currentIndex).getKChartView().changeWR();
                    kChartPop.dismiss();

                });
                ClickUtil.click(ivDownToggle, () -> {
                    if (isDownToggle) {
                        isDownToggle = false;
                        ivDownToggle.setImageResource(R.mipmap.app_icon_hide);

                        fragmentList.get(currentIndex).getKChartView().setDrawDown(isDownToggle);
                    } else {
                        isDownToggle = true;
                        ivDownToggle.setImageResource(R.mipmap.app_icon_show);

                        fragmentList.get(currentIndex).getKChartView().setDrawDown(isDownToggle);
                    }
                    kChartPop.dismiss();

                });
                kChartPop.setBackground(0);
            }
            if (kChartPop.isShowing()) {
                kChartPop.dismiss();
            } else {
                kChartPop.showPopupWindow(commonTabLayout);
            }
        });
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add((Fragment) ARouter.getInstance()
                .build(RConfig.APP_FRAGMENT_DEEPTH)
                .withString(Constans.CODE, code)
                .navigation());
//        fragments.add((Fragment) ARouter.getInstance()
//                .build(RConfig.APP_FRAGMENT_TRADE)
//                .withString(Constans.CODE, code)
//                .navigation());
        fragments.add((Fragment) ARouter.getInstance()
                .build(RConfig.APP_FRAGMENT_TRADE)
                .withString(Constans.CODE, code)
                .navigation());
        fragments.add((Fragment) ARouter.getInstance()
                .build(RConfig.APP_FRAGMENT_SUMMARY)
                .withString(Constans.CODE, code)
                .navigation());
        viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments));
//        slidingTabLayout.setViewPager(viewPager, new String[]{App.INSTANCE.getString(R.string.hang_marketActivity11_j), App.INSTANCE.getString(R.string.hang_marketActivity12_j), App.INSTANCE.getString(R.string.hang_marketActivity13_j)});
        slidingTabLayout.setViewPager(viewPager, new String[]{App.INSTANCE.getString(R.string.hang_marketActivity11_j),App.INSTANCE.getString(R.string.hang_marketActivity12_j), App.INSTANCE.getString(R.string.hang_marketActivity13_j)});
        viewPager.addHeight(0, (int) RudenessScreenHelper.pt2px(App.INSTANCE, 1800));
        viewPager.addHeight(1, (int) RudenessScreenHelper.pt2px(App.INSTANCE, 1800));
        viewPager.addHeight(2, (int) RudenessScreenHelper.pt2px(App.INSTANCE, 1000));

    }

    @Override
    protected void initData() {
//        mPresenter.getProduct();
        mPresenter.getData(code);
    }

    private void initTab() {
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {

                if (position < 5) {
                    tvMore.setText(App.INSTANCE.getString(R.string.hang_marketActivity14_j));
                }
                selectTab(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        selectTab(0);
    }

    /**
     * k线切换
     *
     * @param index
     */
    private void selectTab(int index) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ChartFragment minuteFragment = fragmentList.get(index);
        ChartFragment currentFragment = fragmentList.get(currentIndex);
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }
        if (minuteFragment == null) {
            if (index == 0) {
                minuteFragment = (ChartFragment) ARouter.getInstance()
                        .build(RConfig.APP_FRAGMENT_CHART)
                        .withString(Constans.CODE, code)
                        .withString(Constans.GOOD_TYPE, goodsType[index])
                        .withBoolean(Constans.IS_CANDLE, false)
                        .navigation();
            } else {
                minuteFragment = (ChartFragment) ARouter.getInstance()
                        .build(RConfig.APP_FRAGMENT_CHART)
                        .withString(Constans.CODE, code)
                        .withString(Constans.GOOD_TYPE, goodsType[index])
                        .withBoolean(Constans.IS_CANDLE, true)
                        .navigation();
            }
            fragmentList.set(index, minuteFragment);
            ft.add(R.id.frameLayoutChart, minuteFragment);
        } else {
            ft.show(minuteFragment);
        }
        ft.commitNowAllowingStateLoss();
        currentIndex = index;
    }


    public void updateSpiner(List<CoinBean> data) {
        if (data == null || data.size() == 0)
            return;
        Flowable.fromIterable(data)
                .map(coinBean -> coinBean.getCode().toUpperCase())
                .toList()
                .subscribe(strings -> {
                    ClickUtil.click(tvTitle, () -> {
                        if (spinnerPop == null) {
                            spinnerPop = PopUtil.popSpinner(this, (recyclerView, position, v) -> {
                                spinnerPop.dismiss();
                                tvTitle.setText(strings.get(position).replace("_", "/").toUpperCase());
                                code = data.get(position).getCode();
                                mPresenter.getData(code);
                                RxBus.getDefault().post(new MarketCoinBean(code,qu));
                            }, strings);
                        }
                        spinnerPop.showPopupWindow(tvTitle);
                    });
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(CoinBean data) {
        if (data.getCode().equals(code)) {
//            btTrade.setBackground(ContextCompat.getDrawable(App.INSTANCE, data.isUp() ? R.drawable.app_shape_corner45_03c : R.drawable.app_shape_corner45_ff5));
            tvUSDT.setText(data.getPrice());
            tvRMB.setText(String.format("≈%s "+Constans.DANWEI, CommonUtil.dealCNY(data.getCnyPrice())));
            tvRate.setText(data.getChangeRate());
            tvLow.setText(CoinUtil.keepCoinPrice(code, data.getLow()));
            tvHigh.setText(CoinUtil.keepCoinPrice(code, data.getHigh()));
            tvVolume.setText(Double.valueOf(data.getVolume()).intValue() + "");
            tvUSDT.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
            tvRate.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        }
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }
}

